package cn.milolab.djback.service;

import cn.milolab.djback.bean.entity.Employee;
import cn.milolab.djback.bean.entity.User;
import cn.milolab.djback.conf.DjException;
import cn.milolab.djback.dao.EmployeeDAO;
import cn.milolab.djback.dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 叶欣委
 */
@Service
public class AuthenticateService {

    @Autowired
    UserDAO userDAO;
    @Autowired
    EmployeeDAO employeeDAO;

    public Map<String, Object> authenticate(String stuSerial, String jobSerial, Integer userId) {

        System.out.println(userId==null);
        System.out.println(userId);
        //通过userid获得User
        User user = userDAO.getUserById(userId);

        //通过stuSerial和jobSerial获得Employee
        Employee employee = employeeDAO.getEmployeeBySerial(stuSerial, jobSerial);

        //判断学号工号是否正确
        if (employee == null) {
            throw DjException.requestLogicError("学号或者工号错误");
        } else {
            //将userId更新如employee表中
            Integer res = employeeDAO.updateUserId(employee.getId(), user.getId());

            if (res != 1) {
                throw DjException.internalServerError("无法更新社员信息");
            }
            //重新更新employee对象
            employee.setUserId(user.getId());
            //将返回结果放入Map中
            HashMap<String, Object> result = new HashMap<>(2);
            result.put("user", user);
            result.put("employee", employee);
            return result;
        }
    }
}
